import {
  Button,
  Message,
  Modal,
  Form,
  Input,
  Upload,
  Select,
} from "@arco-design/web-react";
import { IconEdit, IconUpload, IconPlus } from "@arco-design/web-react/icon";
import React, { memo, useEffect, useState, type FC } from "react";
import { ArticleWrapper } from "../style";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import useForm from "@arco-design/web-react/es/Form/useForm";
import { useAppDispatch, useAppSelector } from "../../../../store";
import {
  fetchAddArticleAction,
  fetchGetDetailInfoAction,
  fetchUpdateArticleAction,
} from "../../../../store/modules/article";
import { BASE_URL } from "../../../../service/config";
import { getCurrentToken } from "../../../../service/modules/login";
import type { UploadItem } from "@arco-design/web-react/es/Upload";
const FormItem = Form.Item;
const Option = Select.Option;

interface IArtileParams {
  comments?: number | null;
  content: string | null;
  createBy: string | null;
  createTime: string | null;
  id: number | null;
  image: string | null;
  likes: number | null;
  remark?: string | null;
  state: string;
  sysDeptId: number | null;
  sysUserId?: null | number;
  title: string | null;
  updateBy: string | null;
  updateTime: string | null;
  userId?: null | number;
}
interface UploadResponse {
  msg: string;
  fileName: string;
  code: number;
  newFileName: string;
  url: string;
  originalFilename: string;
}
interface ModifyArticleProps {
  visible: boolean;
  mode: "add" | "edit";
  id: number | null;
  onClose: () => void;
  onCloseSelected: () => void;
  onRefresh: () => void;
}

const ModifyArticle: FC<ModifyArticleProps> = ({
  visible,
  mode,
  id,
  onClose,
  onCloseSelected,
  onRefresh,
}) => {
  const dispatch = useAppDispatch();
  const token = getCurrentToken();
  const [form] = useForm();
  const [content, setContent] = useState("");
  const [fileList, setFileList] = useState<UploadItem[]>([]);
  const { articleDetail } = useAppSelector((state) => state.article);

  useEffect(() => {
    if (!visible) return;
    else {
      if (mode === "edit" && id) {
        dispatch(fetchGetDetailInfoAction(id));
      }
    }
  }, [visible, mode, id]);
  //*初始化修改新增
  useEffect(() => {
    if (!visible) return;
    if (articleDetail && mode === "edit") {
      form.setFieldsValue({
        title: articleDetail.title,
        state: articleDetail.state,
        image: articleDetail.image,
      });
      setContent(articleDetail.content || "");
      if (articleDetail.image) {
        setFileList([
          {
            uid: "-1",
            name: "articleimg",
            url: `http://119.29.235.74:20242${articleDetail?.image}`,
            status: "done",
          },
        ]);
      }
    } else if (mode === "add") {
      form.resetFields();
      setContent("");
      setFileList([]);
    }
  }, [articleDetail, visible, mode]);

  const handleOk = async () => {
    //*验证表单数据，返回表单数据
    const values = await form.validate();
    // console.log(values);
    //*提供相对路径
    const image = values.image?.replace("http://119.29.235.74:20242", "");
    // setArticleParams(values);
    const editBody = {
      // comments: articleDetail?.comments,
      // content: content,
      // createBy: articleDetail?.createBy,
      // createTime: articleDetail?.createTime,
      // id: articleDetail?.id,
      // image: image,
      // likes: articleDetail?.likes,
      // remark: articleDetail?.remark,
      // state: articleDetail?.sttate,
      // sysDeptId: articleDetail?.sysDeptId,
      // title: values?.title,
      // updateBy: articleDetail?.updateBy,
      // updateTime: articleDetail?.updateTime,
      // userId: articleDetail?.userId,
      ...articleDetail,
      ...values,
      image,
      content,
    };
    // console.log(body);
    const addBody = {
      content: content,
      createBy: null,
      createTime: null,
      id: null,
      image: image,
      likes: null,
      state: values.state,
      sysDeptId: null,
      sysUserId: null,
      title: values.title,
      updateBy: null,
      updateTime: null,
    };
    if (mode === "edit") {
      await dispatch(fetchUpdateArticleAction(editBody));
      Message.success("修改成功");
    } else {
      await dispatch(fetchAddArticleAction(addBody));
      Message.success("新增成功");
    }
    onRefresh();
    onCloseSelected();
    onClose();
  };

  /**
   * @富文本编译器
   */
  const modules = {
    toolbar: [
      [{ header: [1, 2, 3, false] }], // 标题
      ["bold", "italic", "underline", "strike"], // 加粗、斜体、下划线、删除线
      [{ color: [] }, { background: [] }], // 文字颜色、背景色
      [{ list: "ordered" }, { list: "bullet" }], // 列表
      [{ indent: "-1" }, { indent: "+1" }], // 缩进
      ["blockquote", "code-block"], // 引用、代码块
      ["link", "image"], // 链接、图片
      ["clean"], // 清除格式
    ],
    //*历史记录，控制撤销，重做行为
    history: {
      delay: 500, //多久算一次
      maxStack: 100,
      userOnly: true,
    },
  };
  const formats = [
    "header",
    "bold",
    "italic",
    "underline",
    "strike",
    "color",
    "background",
    "list",
    "bullet",
    "indent",
    "blockquote",
    "code-block",
    "link",
    "image",
  ];
  return (
    <ArticleWrapper>
      <Modal
        title={mode === "add" ? "新增文章" : "修改文章"}
        visible={visible}
        onOk={handleOk}
        onCancel={() => {
          onClose();
          onCloseSelected();
        }}
      >
        <Form form={form}>
          <FormItem label="文章标题" field="title">
            <Input />
          </FormItem>
          <FormItem label="上传图片" field="image">
            {/* <Upload
            
              listType="picture-card"
              // fileList={fileList}
              action="http://119.29.235.74:20243/prod-api/common/upload"
              headers={{
                Authorization: `Bearer ${token}`,
              }}
              name="file"
              limit={1}
              // showUploadList={false}
              onChange={(newFileList, currentFile) => {
                console.log(currentFile);
                console.log(newFileList);

                if (currentFile.status === "done") {
                  Message.success("上传成功");
                  const res = currentFile.response as UploadResponse;
                  const updatedList = newFileList.map((file) =>
                    file.uid === currentFile.uid
                      ? { ...file, url: res.url }
                      : file
                  );
                  setFileList(updatedList);
                  form.setFieldValue("image", res.url);
                }
              }}
              beforeUpload={(file) => {
                if (file.size > 2 * 1024 * 1024) {
                  Message.error("文件不能超过2MB");
                  return false;
                }
                return true;
              }}
            >
              {fileList && fileList[0]?.url ? (
                <div className="arco-upload-list-item-picture custom-upload-avatar">
                  <img src={fileList[0]?.url} />
                  <div className="arco-upload-list-item-picture-mask">
                    <IconEdit />
                  </div>
                </div>
              ) : (
                <div className="arco-upload-trigger-picture">
                  <div className="arco-upload-trigger-picture-text">
                    <IconPlus />
                    <div style={{ marginTop: 10, fontWeight: 600 }}>Upload</div>
                  </div>
                </div>
              )}
            </Upload> */}
            <Upload
              listType="picture-card"
              fileList={fileList}
              onPreview={(file) => {
                console.log(file);
                Modal.info({
                  title: "图片预览",
                  content: <img src={file?.url} style={{ width: "100%" }} />,
                  okText: "关闭",
                });
              }}
              action={`${BASE_URL}/common/upload`}
              headers={{
                Authorization: `Bearer ${token}`,
              }}
              name="file"
              limit={1}
              onChange={(newFileList, currentFile) => {
                if (currentFile.status === "done") {
                  Message.success("上传成功");
                  const res = currentFile.response as UploadResponse;
                  // console.log(res);
                  // console.log(newFileList);

                  const updatedList = newFileList.map((file) =>
                    file.uid === currentFile.uid
                      ? { ...file, url: res?.url }
                      : file
                  );
                  setFileList(updatedList);
                  form.setFieldValue("image", res?.fileName);
                } else {
                  setFileList(newFileList);
                }
              }}
              beforeUpload={(file) => {
                if (file.size > 2 * 1024 * 1024) {
                  Message.error("文件不能超过2MB");
                  return false;
                }
                return true;
              }}
            />
          </FormItem>
          <FormItem label="发布状态" field="state">
            <Select>
              <Option value="1">发布</Option>
              <Option value="0">未发布</Option>
            </Select>
          </FormItem>
          <FormItem label="内容">
            <ReactQuill
              value={content}
              onChange={setContent}
              theme="snow"
              modules={modules}
              formats={formats}
            />
          </FormItem>
        </Form>
      </Modal>
    </ArticleWrapper>
  );
};
export default memo(ModifyArticle);
